import json

import numpy as np
import pandas as pd
import yaml
from yaml import SafeLoader

from datareport.api import ConfigClass
from datareport.api.DataSource import DataSource
from datareport.api.annotation.Font import Font
from datareport.api.enum.ColorEnum import ColorEnum
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style
from datareport.api.enum.ParagraphStyleEnum import ParagraphStyleEnum


@style()
class XiaoJi_GuanMoQingKuang_28(BaseParagraph):
    """
    观摩情况
    """

    def __init__(self):
        super().__init__()
        self.text = '''1、整体观摩情况: 累计观摩{}场次，参与观摩支部书记{}人(累计{}次)，有外部组织观摩占全年观摩场次的{}。'''
        self.fonts=[

        ]
        self.sort = 17
        self.section = 4

    def plot(self, df, plt):
        pass

    def getData(self, result):
        pass

    def start(self, conn, year, plt):
        conn1 = DataSource(ConfigClass.data['datasource1']).conn
        df=pd.read_sql('''select observer,partyBranchName,partyOrgName 
        from t_meetingInfo where observer is not null and completeStatus='通过'
        ''',con=conn)
        user=pd.read_sql('''select 学工号,党组织名称 from v_dysfzinfo 
        ''',con=conn1)
        changci=len(df) # 场次
        observers=[]
        renci=0 #人次
        hasExter=np.zeros(len(df))
        for i,ob in enumerate(df['observer'].values.tolist()):
            temp=json.loads(ob)
            renci+=len(temp)
            external=0
            for t in temp:
                if t['code'] not in observers:
                    observers.append(t['code'])
                if external==0:
                    if user[user['学工号']==t['code']]['党组织名称'].values[0]!=df.iloc[i].at['partyOrgName']:
                        external+=1
            if external>0:
                hasExter[i]=1

        renshu=len(observers)
        df['hasexter']=hasExter
        self.fonts.append(Font(text=self.text.format(changci,renshu,renci,round(df['hasexter'].mean(),1))))


if __name__ == '__main__':
    with open('D:\work\sanhuiyike\datareport\config.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)
    con = DataSource(data['datasource']).conn
    XiaoJi_GuanMoQingKuang_28().start(con, 2023, '')